<?php

namespace app\api\controller\plus\discount;

use app\api\model\plus\discount\Active as DiscountActiveModel;
use app\api\model\plus\discount\Product as ProductModel;
use app\common\model\plus\discount\DiscountGitOrder;
use app\api\model\user\UserAddress;
use app\api\service\order\settled\DiscountOrderSettledService;
use app\api\controller\Controller;
use app\api\model\settings\Message as MessageModel;
use app\api\model\order\Order as OrderModel;
use app\api\service\pay\PayService;
use app\common\enum\order\OrderTypeEnum;
use app\common\library\helper;
use app\common\model\plus\discount\DiscountGitProduct;

/**
 * 限时秒杀订单
 */
class Order extends Controller
{
    /**
     * 订单确认
     */
    public function buy()
    {
        // 限时秒杀订单：获取订单商品列表
        $params = json_decode($this->postData()['params'], true);

        $user = $this->getUser();
        $supplierData = ProductModel::getDiscountProduct($params,$user);

        // 实例化订单service
        $orderService = new DiscountOrderSettledService($user, $supplierData, $params);

        // 获取订单信息
        $orderInfo = $orderService->settlement();

        $is_gift = $supplierData[0]['discount_info']['is_gift']??0;
        $gift_num = $supplierData[0]['discount_info']['gift_num']??0;
        $gift_product_id = $supplierData[0]['discount_info']['gift_product_id']??0;
        $image_id = $supplierData[0]['discount_info']['image_id']??0;
        $product_id = $supplierData[0]['discount_info']['product_id']??0;
        if($is_gift==1){
            //赠品信息
            $gift_product_data = (new DiscountGitProduct()) -> with(['file'])->where(['is_delete'=>0]) -> where('gift_product_id',$gift_product_id) -> find();
            $gift_product_data['gift_num'] = $gift_num;
            if($gift_product_id>0){
                $orderInfo['gift_product_data'] = $gift_product_data;
            }
        }

        if ($this->request->isGet()) {
            // 如果来源是小程序, 则获取小程序订阅消息id.获取支付成功,发货通知.
            $template_arr = MessageModel::getMessageByNameArr($params['pay_source'], ['order_pay_user', 'order_delivery_user']);
            // 是否开启支付宝支付
            $show_alipay = PayService::isAlipayOpen($params['pay_source'], $user['app_id']);
            $balance = $user['balance'];
            return $this->renderSuccess('', compact('orderInfo', 'template_arr', 'show_alipay', 'balance'));
        }
        // 订单结算提交
        if ($orderService->hasError()) {
            return $this->renderError($orderService->getError());
        }
        $orderInfo['orderData']['store_id'] = $params['store_id'];
        $orderInfo['orderData']['buytype'] = $params['buytype'];
        $orderInfo['orderData']['yypstime'] = $params['yypstime'];
        if (array_key_exists('addr_id', $params)) {
            $addr = UserAddress::where('address_id', '=', $params['addr_id'])->find();
            if (empty($addr)) return $this->renderError($orderService->getError() ?: '地址异常');
            $orderInfo['orderData']['address'] = $addr;
        }
        $checkPTS = OrderModel::checkAddrPointToStore($addr,$params['store_id']);
        if(!$checkPTS){
            return $this->renderError($orderService->getError() ?: '地址不在店铺配送范围');
        }
        foreach ($orderInfo['supplierList'] as $sval) {
            $checkSWP = OrderModel::checkStoreWithProduct($params['store_id'],$sval['productList']);
            if(!$checkSWP){
                return $this->renderError($orderService->getError() ?: '地址不在店铺配送范围');
            }
        }
        //检测休息
        $checkXX = OrderModel::checkStoreRest($params['store_id']);
        if(!$checkXX){
            return $this->renderError($orderService->getError() ?: '店铺已打烊休息');
        }
        try {
            // 创建订单
            $order_id = $orderService->createOrder($orderInfo);
            if (!$order_id) {
                return $this->renderError($orderService->getError() ?: '订单创建失败');
            }

            if($is_gift == 1){ //等于1则赠送礼品
                $gift_data['order_id'] = $order_id[0];
                $gift_data['user_id'] = $user['user_id'];
                $gift_data['gift_product_id'] = $gift_product_id;
                $gift_data['order_total_num'] = $gift_num;
                $gift_data['image_id'] = $image_id;
                $gift_data['product_id'] = $product_id; //商品的id
                DiscountGitOrder::createData($gift_data);

            }

        } catch (\Exception $exception) {
            return $this->renderError($exception->getMessage() ?: '订单创建失败');
        }

        // 返回订单信息
        return $this->renderSuccess('', [
            'order_id' => $order_id,   // 订单号
        ]);
    }
}
